﻿/*******************************************************************************
Copyright (c) 2011-2013, PKStudio

http://pkstudio.org

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*******************************************************************************/

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;

namespace PKEngine
{
	/// <summary>
	/// Binary font of PKEngine.
	/// </summary>
	public class PKBinFont
	{
		#region Constant
		private const uint PkbfHeader = 0x46424b50;
		private const int CharDataHeaderSize = 1;
		#endregion

		#region Private Fields
		private Dictionary<ushort, int> charDict;
		private byte[] charData;
		#endregion

		#region Public Properties
		public List<char> CharacterList { get; private set; }
		public string Name { get; private set; }
		public int CommandHeight { get; private set; }
		public int Wide { get; private set; }
		public bool IsEmpty { get { return charDict == null; } }
		#endregion

		#region Initialization
		public PKBinFont(string filePath)
		{
			Debug.Assert(!string.IsNullOrEmpty(filePath), "PKBinFont: Argument cannot be null.");
			Debug.Assert(File.Exists(filePath), "PKBinFont: Cannot find file.");

			this.Name = filePath.ToLower();
			using (BinaryReader reader = new BinaryReader(File.Open(filePath, FileMode.Open)))
			{
				Debug.Assert(reader.ReadUInt32() == PkbfHeader, "PKBinFont: Invalid bin font header.");

				int length = reader.ReadUInt16();
				this.Wide = reader.ReadByte();
				this.CommandHeight = reader.ReadByte();

				int size = this.Wide * this.CommandHeight + CharDataHeaderSize;
				this.CharacterList = new List<char>(length);
				this.charDict = new Dictionary<ushort, int>(length);
				for (int i = 0; i < length; i++)
				{
					ushort current = (char)reader.ReadUInt16();
					this.CharacterList.Add((char)current);
					this.charDict.Add(current, i * size);
				}
				this.charData = reader.ReadBytes(length * size);
			}
		}
		#endregion

		#region Public Methods
		/// <summary>
		/// Get the width of a string.
		/// </summary>
		/// <param name="text">Specified string</param>
		/// <param name="spacing">Spacing</param>
		/// <returns>Width of string</returns>
		public int MeasureString(string text, int spacing)
		{
			int stringWidth = 0;

			ushort current;
			int offset;
			foreach (char ch in text)
			{
				if (ch == '\n')
				{
					break;
				}

				current = (ushort)ch;
				if (charDict.ContainsKey(current))
				{
					offset = charDict[current];
					stringWidth += charData[offset] + spacing;
				}
			}
			if (stringWidth > 0)
			{
				stringWidth -= spacing;
			}

			return stringWidth;
		}

		/// <summary>
		/// Draw a one line string to specified surface.
		/// </summary>
		/// <param name="text">Specified string</param>
		/// <param name="surface">Target surface</param>
		/// <param name="startPoint">Target point</param>
		/// <param name="spacing">Spacing</param>
		/// <returns>The cursor position after drawing string</returns>
		public Point DrawString(string text, PKSurface surface, Point startPoint, int spacing)
		{
			ushort current;
			int offset;
			int width;
			foreach (char ch in text)
			{
				if (ch == '\n')
				{
					break;
				}

				if (!CharacterList.Contains(ch))
				{
					Debug.Print("PKLabelBinFont.CreateCharSpritesHelper: Characer not found.");
					continue;
				}

				current = (ushort)ch;
				offset = charDict[current];
				width = charData[offset];
				for (int y = 0; y < CommandHeight; y++)
				{
					for (int x = 0; x < width; x++)
					{
						switch (this.GetCharDataBit(x + y * Wide * 4, offset))
						{
							case 1:
								surface.SetPixel(startPoint.X + x, startPoint.Y + y, PKAlpha.SharedAlpha.ColorWhite);
								break;
							case 2:
								surface.SetPixel(startPoint.X + x, startPoint.Y + y, PKAlpha.SharedAlpha.ColorBlack);
								break;
						}
					}
				}

				startPoint.X += width + spacing;
			}

			return startPoint;
		}
		#endregion

		#region Private Methods
		private int GetCharDataBit(int index, int offset)
		{
			int position = offset + index / 4 + CharDataHeaderSize;
			int move = (index % 4) * 2;
			return (charData[position] >> move) & 0x3;
		}
		#endregion
	}
}
